<template>
  <!-- 确认个人信息 -->
  <div class="app-container-add">
    <el-row :gutter="10" class="button-wrap" :style="{width:mainContentWidth + 'px','left':'80px'}">
      <el-col :span="1.5">
        <el-button icon="el-icon-arrow-left" size="middle" @click="handleReturn()">返回</el-button>
      </el-col>
      <el-col v-if="msgType && status === '2'" :span="1.5">
        <el-button v-clickForbidden icon="el-icon-document-checked" :disabled="isBtnDisa" size="middle" @click="handleConfirm(true)">确认</el-button>
      </el-col>
      <el-col v-if="msgType && status === '2'" :span="1.5">
        <el-button v-clickForbidden icon="el-icon-document" :disabled="isBtnDisa" size="middle" @click="handleConfirm()">拒绝</el-button>
      </el-col>
    </el-row>
    <div class="main-content">
      <el-card ref="mainContent" class="box-card" shadow="never">
        <div class="main-content-body">
          <el-form ref="formData" class="data-form" :rules="userRules" :model="formData" label-width="80px">
            <div class="data-form-item">
              <div class="two-level-title">基本信息</div>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="用户名称" prop="name">
                    <el-input v-model="formData.name" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="formData.phone" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="用户邮箱" prop="email">
                    <el-input v-model="formData.email" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="用户性别" prop="sex">
                    <el-select style="width:100%" class="remove-arrow" :value="formData.sex" disabled placeholder="请选择">
                      <el-option
                        v-for="item in sexOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="创建日期" prop="createTime">
                    <el-input v-model="formData.createTime" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="归属部门" prop="deptId">
                    <treeselect
                      v-model="formData.deptId"
                      :options="deptOptionsAll"
                      :disabled="status !== '2'"
                      placeholder="请选择归属部门"
                      size="medium"
                      no-options-text="暂无数据"
                      :normalizer="normalizer"
                      :disable-branch-nodes="true"
                      @input="updateDeptType"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="岗位分类" prop="postIds">
                    <el-select
                      v-model="formData.postIds"
                      multiple
                      filterable
                      :disabled="status !== '2'"
                      style="width:100%"
                      default-first-option
                      placeholder="请选择岗位"
                      size="medium"
                      class="remove-arrow"
                    >
                      <el-option
                        v-for="item in postOptions"
                        :key="item.postId"
                        :label="item.postName"
                        :value="item.postId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="角色" prop="roleIds" size="medium">
                    <label slot="label" v-html="`角&emsp;&emsp;色`" />
                    <el-select
                      v-model="formData.roleIds"
                      style="width:100%"
                      multiple
                      filterable
                      :disabled="status !== '2'"
                      default-first-option
                      placeholder="请选择角色"
                      size="medium"
                      class="remove-arrow"
                    >
                      <el-option
                        v-for="item in roleOptions"
                        :key="item.roleId"
                        :label="item.roleName"
                        :value="item.roleId"
                        size="medium"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="权限范围" prop="dataScope" size="medium">
                    <el-select v-model="formData.dataScope" class="remove-arrow" :disabled="status !== '2'" style="width:100%">
                      <el-option
                        v-for="dict in dataScopeOptions"
                        :key="dict.dictValue"
                        size="medium"

                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                      />
                    </el-select>
                    <div style="color:red">该用户拥有菜单的默认数据权限</div>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="备注信息" prop="remark">
                    <el-input
                      v-model="formData.remark"
                      :disabled="status !== '2'"
                      type="textarea"
                      size="medium"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <!--证件信息-->
              <!-- <el-row>
                <certificateList :edit="edit" title="证件信息" />
              </el-row> -->
            </div>
          </el-form>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
// 树型选择引入
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// 引入角色 中查询list方法
import { listRoleAll } from '@/api/system/role'
import { listPostAll } from '@/api/system/post'
import { selectAllEnterpDeptTree, getDeptTree, getDeptByDeptId } from '@/api/system/dept'
import { mapState } from 'vuex'
import { sysAccountGetById } from '@/api/common/approvalReminder'
import { updateAccountStatus } from '@/api/system/enterpriseRecord/index'
export default {
  name: 'CompanyInfo',
  components: {
    Treeselect
  },
  data() {
    // 查看选择的归属部门是不是分公司
    const validSubCompany = (rule, value, callback) => {
      if (this.deptType === '0') {
        return callback(new Error('所属部门不能选择公司'))
      } else {
        callback()
      }
    }
    return {
      mainContentWidth: '',
      deptType: '',
      deptOptionsAll: [],
      deptOptions: undefined,
      normalizer(node) {
        return {
          id: node.deptId,
          label: node.deptName,
          children: node.children
        }
      },
      // 角色选择
      roleOptions: [],
      // 岗位选择
      postOptions: [],
      // 数据范围选项 1：全部数据权限3：本部门数据权限 4：本部门及以下数据权限 5：仅本人数据权限
      dataScopeOptions: [],
      msgType: '',
      status: '', // 人员状态
      isBtnDisa: false,
      sexOptions: [
        { value: '0', label: '男' },
        { value: '1', label: '女' },
        { value: '2', label: '未知' }
      ],
      edit: '0', // 0:不可编辑   1:编辑
      /* 信息 start */
      formData: {
        name: '', // 用户名
        phone: '', // 电话
        email: '', // 邮箱
        createTime: '', // 创建时间
        sex: '', // 性别
        deptId: null,
        postIds: [],
        roleIds: [],
        dataScope: '',
        remark: ''
      },
      // 搜索添加验证
      userRules: {
        deptId: [
          { required: true, message: '归属部门不能为空', trigger: 'blur' },
          { required: true, validator: validSubCompany, trigger: 'blur' }
        ],
        dataScope: [
          { required: true, message: '权限范围是必选项', trigger: 'blur' }
        ]
      },
      queryObj: {
        sysApplyRecord: {}
      }
      /* 信息 end */
    }
  },
  computed: {
    ...mapState({ userId: state => state.user.userInfo.userId })
  },
  watch: {
    queryObj: {
      deep: true,
      immediate: true,
      handler(value) {
        const { messageId, msgType, status, sysApplyRecord: { accountId, id }} = this.queryObj
        this.msgType = msgType
        this.messageId = messageId
        this.status = status || ''
        if (accountId) this.getlist({ accountId, id }) // 获取当前用户信息
        this.selectDeptTree()
        this.selectRoleOptions()
        this.selectPostOptions()
        // 角色数据权限
        this.getDicts('role_data_scope').then(response => {
          this.dataScopeOptions = response.data.rows
        })
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    const message = sessionStorage.getItem('message')
    if (!message) {
      sessionStorage.setItem('message', JSON.stringify(to.query))
      next(vm => {
        vm.queryObj = to.query
      })
    } else {
      next(vm => {
        vm.queryObj = JSON.parse(message)
      })
    }
  },
  beforeRouteLeave(to, from, next) {
    sessionStorage.removeItem('message')
    next()
  },
  mounted() {
    /** 获取主题内容宽度 start*/
    setTimeout(() => {
      this.mainContentWidth = this.$refs.mainContent.$el.offsetWidth
    }, 100)
    const that = this
    window.onresize = () => {
      return (() => {
        that.mainContentWidth = that.$refs.mainContent.$el.offsetWidth
      })()
    }
    /** 获取主题内容宽度 end*/
  },
  methods: {
    // 部门树变化
    updateDeptType(val) {
      if (val) this.getDeptType(val)
    },
    // 获取当前用户信息
    async getlist(params) {
      this.isBtnDisa = true
      const { data: { sysAccount, sysApplyRecord, sysUser }} = await sysAccountGetById(params)
      this.status = sysApplyRecord.status
      if (sysUser) {
        this.formData = { ...sysAccount, ...sysApplyRecord.status, ...sysUser }
        if (sysUser.roles) {
          this.formData.roleIds = sysUser.roles.map(item => { return item.roleId })
        }
      } else {
        this.formData = { ...sysAccount, ...sysApplyRecord.status }
      }
      this.isBtnDisa = false
    },
    // 查找角色表的所有信息
    selectRoleOptions() {
      listRoleAll().then(resp => {
        if (resp) {
          this.roleOptions = resp.data.rows
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 查找岗位表的所有信息
    selectPostOptions() {
      listPostAll().then(resp => {
        if (resp) {
          this.postOptions = resp.data.rows
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 部门选择树列表
    selectDeptTree() {
      selectAllEnterpDeptTree().then(resp => {
        if (resp) {
          if (resp.data !== null) {
            this.deptOptionsAll = this.deleteChildren(resp.data)
          }
        }
      })
      getDeptTree().then(resp => {
        if (resp) {
          this.deptOptions = resp.data
        }
      })
    },
    // 获取公司类型
    getDeptType(value) {
      getDeptByDeptId(value).then(resp => {
        if (resp) {
          this.deptType = resp.data.deptType
        }
      })
    },
    // 返回
    handleReturn() {
      this.$router.go(-1)
    },
    // 审批
    handleConfirm(isAgree) {
      const { deptId, postIds, roleIds, dataScope, remark } = this.formData
      const userJson = { deptId, postIds, roleIds, dataScope, remark }
      const { sysApplyRecord, messageId } = this.queryObj
      if (isAgree) {
        this.$refs['formData'].validate(valid => {
          if (valid) {
            this.$confirm('是否同意加入?', '提示', {
              confirmButtonText: '同意',
              cancelButtonText: '取消'
            }).then(async() => { // 同意审批
              const { code, message } = await updateAccountStatus({
                ...sysApplyRecord,
                messageId,
                status: '0',
                userJson: JSON.stringify(userJson)
              })
              if (code === 200) {
                this.msgSuccess('审批成功')
                this.$router.go(-1)
              } else if (code === 202) {
                this.msgWarning(message)
                this.$router.go(-1)
              }
            }).catch(() => {
            })
          }
        })
      } else { // 审批被拒绝
        this.$confirm('是否拒绝加入', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(async() => {
          const { code } = await updateAccountStatus({ ...sysApplyRecord, messageId, status: '1' })
          if (code === 200) {
            this.msgWarning('已拒绝')
            this.$router.go(-1)
          }
        }).catch(() => {
        })
      }
    }
  }
}
</script>

<style lang='scss'>
// .remove-arrow {
//   .el-icon-arrow-up {
//     color: red;
//   }
//   .el-icon-arrow-up::before {
//     content: " ";
//   }
// }
</style>
